import time
import threading
from datetime import datetime
from app.services.schedule_service import ScheduleService
from app.utils.logger import logger

class Scheduler:
    """定时任务调度器"""
    
    def __init__(self, check_interval=60):
        """
        初始化调度器
        :param check_interval: 检查间隔（秒），默认60秒
        """
        self.check_interval = check_interval
        self.running = False
        self.thread = None
    
    def start(self):
        """启动调度器"""
        if self.running:
            logger.warning("调度器已在运行中")
            return
        
        self.running = True
        self.thread = threading.Thread(target=self._run, daemon=True)
        self.thread.start()
        logger.info(f"调度器已启动，检查间隔: {self.check_interval}秒")
    
    def stop(self):
        """停止调度器"""
        if not self.running:
            logger.warning("调度器未在运行")
            return
        
        self.running = False
        if self.thread:
            self.thread.join(timeout=5)
        logger.info("调度器已停止")
    
    def _run(self):
        """调度器主循环"""
        # 导入Flask应用以创建应用上下文
        from app import app
        
        while self.running:
            try:
                # 在应用上下文中执行调度任务检查
                with app.app_context():
                    # 检查并执行到期的调度任务
                    executed_count = ScheduleService.check_and_execute_due_schedules()
                    if executed_count > 0:
                        logger.info(f"执行了 {executed_count} 个到期的调度任务")
                
                # 等待下一个检查周期
                time.sleep(self.check_interval)
                
            except Exception as e:
                logger.error(f"调度器执行出错: {str(e)}")
                # 发生错误时继续运行，避免调度器崩溃
                time.sleep(self.check_interval)
        
        logger.info("调度器主循环已退出")

# 全局调度器实例
scheduler = Scheduler()

if __name__ == "__main__":
    # 当直接运行此脚本时，启动调度器
    scheduler.start()
    
    try:
        # 保持脚本运行
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("正在停止调度器...")
        scheduler.stop()
        print("调度器已停止")